# coding: utf8
import datetime
import random
import time
import uuid

import tornado
from django.db.models import F, Q

import cms_config
from app.base_controller import BaseController
# /api/video-list
from app.common import global_space, wzhifuSDK
from app.models import Tag, Video, Serie, Recommend, SerieVideo, User, VideoOrder, VideoElement, OrderElement, OrderProducer, OrderTeam, VideoType, Element, GOrder
from libs.sms.demo_sms_send import send_sms
from libs.util import check_param


def get_random_manager():
    return random.sample([key.id for key in User.objects.filter(user_state=1).all()], 1)[0]


# 视频列表
class IndexVideos(BaseController):

    def get(self):
        tag_id = self.get_argument("tag", '')
        if tag_id:
            tag = Tag.objects.filter(id=tag_id).order_by('show_order').first()
        else:
            tag = Tag.objects.order_by('show_order').first()
        vo = tag.video_set.filter(state=0, video_source=2)
        #
        order = self.get_argument("order", '')
        if order and order == 'play_time':
            vo = vo.order_by(F('play_time') + F('ini_play_time'))
        elif order and order == '-play_time':
            vo = vo.order_by((F('play_time') + F('ini_play_time')).desc())
        elif order and order == 'price':
            vo = vo.order_by('user_price')
        elif order and order == '-price':
            vo = vo.order_by('-user_price')
        else:
            vo = vo.order_by('show_order')
        paginator = self.pagination(vo.all(), number_per_page=int(self.get_argument("pageSize", 10)), page_num=int(self.get_argument("pageNum", 1)), photo_style='/710_476')
        return self.render_json(data=paginator)


# 搜索视频
class SearchVideos(BaseController):

    def get(self):
        keywords = self.get_argument("keywords", '')
        if keywords:
            tags = Tag.objects.filter(name__contains=keywords).all()
            vo = Video.objects
            if tags:
                vo = vo.filter(Q(sub_title__contains=keywords) | Q(title__contains=keywords) | Q(tags__in=tags)).filter(state=0, video_source=2).distinct()
            else:
                vo = vo.filter(Q(sub_title__contains=keywords) | Q(title__contains=keywords)).filter(state=0, video_source=2).distinct()
            vo = vo.order_by('show_order')
            paginator = self.pagination(vo.all(), number_per_page=int(self.get_argument("pageSize", 10)), page_num=int(self.get_argument("pageNum", 1)), photo_style='/710_476')
            return self.render_json(data=paginator)


# 所有标签
class AllTags(BaseController):
    def get(self):
        tags = Tag.objects.filter(state=0).order_by('show_order').all()
        return self.render_json(data=[key.to_dict() for key in tags])


# 推荐列表
class AllRecommend(BaseController):
    def get(self):
        recommends = Recommend.objects.filter(state=0).all()
        return self.render_json(data=[key.to_dict() for key in recommends])


# 系列详情接口
class SerieList(BaseController):
    def get(self):
        id = self.get_argument("id", '')
        param = [id, ]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        s = Serie.objects.filter(id=id).first()
        details = SerieVideo.objects.filter(serie=s, state=0).all()
        data = {'title': s.name, 'videos': [{'img_url': key.img_url, 'vid': key.video.id} for key in details]}
        return self.render_json(data=data)


# 视频详情
class VideoDetail(BaseController):
    def get(self):
        vid = self.get_argument("id", '')
        param = [vid, ]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        vo = Video.objects.filter(id=vid).first()
        return self.render_json(data=vo.v_detail())


# 视频播放
class VideoPlay(BaseController):
    def get(self):
        vid = self.get_argument("id", '')
        param = [vid, ]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        vo = Video.objects.filter(id=vid).first()
        vo.play_time += 1
        vo.save()
        return self.render_json(data={'url': vo.url})


# 订单列表
class OrderList(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=999, msg='session 失效')

        video_orders = VideoOrder.objects.filter(user=user).filter((~Q(order_status__in=[999, 99, 12])))
        video_orders = video_orders.order_by('-create_time')
        paginator = self.pagination(video_orders.all(), number_per_page=int(self.get_argument("pageSize", 10)), page_num=int(self.get_argument("pageNum", 1)), photo_style='/710_476')
        return self.render_json(data=paginator)


# 购物车列表
class CartList(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=999, msg='session 失效')

        video_orders = VideoOrder.objects.filter(user=user).filter(order_status=99)
        video_orders = video_orders.order_by('-create_time')
        paginator = self.pagination(video_orders.all(), number_per_page=int(self.get_argument("pageSize", 10)), page_num=int(self.get_argument("pageNum", 1)), photo_style='/710_476')
        return self.render_json(data=paginator)


# 订单详情
class OrderDetail(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=999, msg='session 失效')
        id = self.get_argument("id", '')
        video_order = VideoOrder.objects.filter(id=id, user=user).first()

        return self.render_json(data=video_order.user_order_detail())


# 定制化订单到购物车
class CreateOrderCustomToCart(BaseController):
    def post(self):
        session_id = self.get_json_argument("session_id", '')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=999, msg='session 失效')
        data_str = time.strftime('%Y%m%d%H%M%S', time.localtime())

        video_type_id = self.get_json_argument("video_type", '')
        shoot_day = self.get_json_argument("shoot_day", '')
        duration = self.get_json_argument("duration", '')
        element_ids = self.get_json_argument("element_ids", '').split(',', )
        element_nums = self.get_json_argument("element_nums", '').split(',', )

        video_type = VideoType.objects.filter(id=video_type_id).first()
        if not video_type:
            return self.render_json(code=1001, msg='视频类型不存在')
        elements = []
        price = 0
        for i in range(len(element_ids)):
            element = Element.objects.filter(id=element_ids[i]).first()
            price = price + element.price
            elements.append(dict(
                element=element,
                num=element_nums[i],
            ))
        order_id = data_str + str(global_space.get_order_id()).zfill(20 - len(data_str))
        video_order = VideoOrder.objects.create(order_status=99, user=user, video_type=video_type, shoot_day=shoot_day, video_duration=duration,
                                                amount=price, price=price, order_id=order_id, producer_type=1, order_from_type=3,
                                                contact=user.contact_name, phone=user.phone, photo_time=datetime.datetime.now()
                                                )
        for key in elements:
            OrderElement.objects.create(order=video_order, element=key['element'], num=key['num'])

        return self.render_json(data=video_order.user_order_detail())


# 创建定制化订单
class CreateOrderCustom(BaseController):
    def post(self):
        session_id = self.get_json_argument("session_id", '')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=999, msg='session 失效')
        data_str = time.strftime('%Y%m%d%H%M%S', time.localtime())

        video_type_id = self.get_json_argument("video_type", '')
        shoot_day = self.get_json_argument("shoot_day", '')
        duration = self.get_json_argument("duration", '')
        element_ids = self.get_json_argument("element_ids", '').split(',', )
        element_nums = self.get_json_argument("element_nums", '').split(',', )

        video_type = VideoType.objects.filter(id=video_type_id).first()
        if not video_type:
            return self.render_json(code=1001, msg='视频类型不存在')
        elements = []
        price = 0
        for i in range(len(element_ids)):
            element = Element.objects.filter(id=element_ids[i]).first()
            price = price + element.price
            elements.append(dict(
                element=element,
                num=element_nums[i],
            ))
        order_id = data_str + str(global_space.get_order_id()).zfill(20 - len(data_str))
        video_order = VideoOrder.objects.create(order_status=999, user=user, video_type=video_type, shoot_day=shoot_day, video_duration=duration,
                                                amount=price, price=price, order_id=order_id, producer_type=1, order_from_type=3,
                                                contact=user.contact_name, phone=user.phone, photo_time=datetime.datetime.now()
                                                )
        for key in elements:
            OrderElement.objects.create(order=video_order, element=key['element'], num=key['num'])

        return self.render_json(data=video_order.user_order_detail())


# 单品或者样片加到购物车
class CreateOrderByVideoToCart(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        id = self.get_argument("id", '')
        num = self.get_argument("num", '')
        if check_param([session_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        v = Video.objects.filter(id=id).first()
        if not v:
            return self.render_json(code=1001, msg='视频不存在')
        if v.video_source == 1:
            price = v.user_price * int(num) + v.extra_price
        else:
            price=v.user_price
        data_str = time.strftime('%Y%m%d%H%M%S', time.localtime())
        order_id = data_str + str(global_space.get_order_id()).zfill(20 - len(data_str))
        video_order = VideoOrder.objects.create(order_status=99, user=user, video_type=v.video_type, shoot_day=v.shoot_day, video_duration=v.duration,
                                                amount=price, price=price, order_id=order_id, producer_type=1, order_from_type=v.video_source, video=v, team=v.team,
                                                contact=user.contact_name, phone=user.phone, photo_time=datetime.datetime.now()
                                                )

        video_elements = VideoElement.objects.filter(video=v).all()
        for key in video_elements:
            OrderElement.objects.create(order=video_order, element=key.element, num=key.num)

        return self.render_json(data=video_order.user_order_detail())


# 单品或者样片下单
class CreateOrderByVideo(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        id = self.get_argument("id", '')
        num = self.get_argument("num", '')

        if check_param([session_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        v = Video.objects.filter(id=id).first()
        if not v:
            return self.render_json(code=1001, msg='视频不存在')

        data_str = time.strftime('%Y%m%d%H%M%S', time.localtime())
        order_id = data_str + str(global_space.get_order_id()).zfill(20 - len(data_str))
        if v.video_source == 1:
            price = v.user_price * int(num) + v.extra_price
        else:
            price=v.user_price
        video_order = VideoOrder.objects.create(order_status=999, user=user, video_type=v.video_type, shoot_day=v.shoot_day, video_duration=v.duration,
                                                amount=price, price=price, order_id=order_id, producer_type=1, order_from_type=v.video_source, video=v, team=v.team,
                                                contact=user.contact_name, phone=user.phone, photo_time=datetime.datetime.now()
                                                )

        video_elements = VideoElement.objects.filter(video=v).all()
        for key in video_elements:
            OrderElement.objects.create(order=video_order, element=key.element, num=key.num)

        return self.render_json(data=video_order.user_order_detail())



# 取消订单
class OrderTotal(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')

        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        return self.render_json(data=dict(
            num=VideoOrder.objects.filter(user=user).filter((~Q(order_status__in=[999, 99, 12]))).count()+GOrder.objects.filter(user=user).filter(~Q(status__in=[99, 14])).count()
        ))


# 取消订单
class OrderCancel(BaseController):
    def get(self):
        session_id = self.get_argument("session_id", '')
        id = self.get_argument("id", '')

        if check_param([session_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        vo = VideoOrder.objects.filter(id=id, user=user).first()
        if not vo:
            return self.render_json(code=1001, msg='订单')
        vo.order_status = VideoOrder.STATE_CACEL
        vo.save()

        return self.render_json()



# 取消订单
class OrderRefund(BaseController):
    def post(self):
        session_id = self.get_json_argument("session_id", '')
        id = self.get_json_argument("id", '')
        back_remark = self.get_json_argument("back_remark", '')

        if check_param([session_id, id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')
        vo = VideoOrder.objects.filter(id=id, user=user).first()
        if not vo:
            return self.render_json(code=1001, msg='订单')
        vo.order_status = VideoOrder.STATE_REFUNDING
        vo.back_remark=back_remark
        vo.save()



        return self.render_json()




# 验收并二次收款
class ToFinish(BaseController):

    @tornado.web.asynchronous
    def post(self):
        session_id = self.get_json_argument("session_id", '')
        if check_param([session_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        id = self.get_json_argument("id", '')
        vo = VideoOrder.objects.filter(id=id, user=user).first()
        if not vo:
            return self.render_json(code=1001, msg='订单不存在')
        data_str = time.strftime('%Y%m%d%H%M%S', time.localtime())
        order_id = data_str + str(global_space.get_order_id()).zfill(20 - len(data_str))

        vo.second_order_id = order_id
        vo.save()
        remote_ip = self.request.remote_ip
        data = {"appid": cms_config.app_id,
                "openid": vo.user.openid,
                "mch_id": cms_config.mch_id,
                "nonce_str": uuid.uuid1().hex,
                "body": "欢玺视频定制",
                "sign_type": "MD5",
                "out_trade_no": str(vo.second_order_id),
                "total_fee": str(vo.price*2//10),
                "spbill_create_ip": remote_ip,
                "notify_url": "https://api.joyfulmedia.cn/api/video-order-notify-second",
                "trade_type": "JSAPI"
                }
        url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'

        sign = wzhifuSDK.get_sign(data)
        data['sign'] = sign
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch(url, method='POST', body=wzhifuSDK.trans_dict_to_xml(data),
                   callback=self.on_response)

    def on_response(self, response):
        if response.error:
            self.render_json(code=1002, msg='系统异常')
        else:
            sign_data = {}
            data = wzhifuSDK.xml_to_dict(response.body.decode('utf-8'))
            if data.get('return_code', '') == 'SUCCESS' and data.get('return_msg', '') == 'OK' and data.get('result_code', '') == 'SUCCESS':
                sign_data['nonceStr'] = uuid.uuid1().hex.upper()
                sign_data['signType'] = 'MD5'
                sign_data['timeStamp'] = str(int(time.time()))
                sign_data['appId'] = cms_config.app_id
                sign_data['package'] = 'prepay_id=' + data.get('prepay_id', '')
                sign_data['sign'] = wzhifuSDK.get_sign(sign_data)
                print(sign_data)
                return self.render_json(data=sign_data)
            else:
                return self.render_json(code=9999, msg='系统错误')


# 二次支付回调
class PayNotifySecond(BaseController):
    def post(self):
        data = wzhifuSDK.xml_to_dict(self.request.body.decode('utf-8'))
        out_trade_no = data.get('out_trade_no')
        total_fee = data.get('total_fee')
        transaction_id = data.get('transaction_id')
        vo = VideoOrder.objects.filter(second_order_id=out_trade_no).first()
        vo.second_weixin_order_id = transaction_id
        vo.pay_amount += int(total_fee)
        vo.secend_pay_amount = int(total_fee)
        vo.order_status = VideoOrder.STATE_PENDING_COMMENTS
        vo.save()
        self.write('''<xml>
                    <return_code>SUCCESS</return_code>
                    <return_msg>OK</return_msg>
                    </xml>''')


# 首次付款
class ToPayByVideo(BaseController):

    @tornado.web.asynchronous
    def post(self):
        session_id = self.get_json_argument("session_id", '')
        if check_param([session_id]):
            return self.render_json(code=1001, msg='参数不全')
        session = global_space.very_session(session_id)
        if not session:
            return self.render_json(code=999, msg='session 失效')
        user = User.objects.filter(id=session['id']).first()
        if not user:
            return self.render_json(code=1001, msg='用户不存在')

        id = self.get_json_argument("id", '')
        photo_time = self.get_json_argument("photo_time", '')
        city = self.get_json_argument("city", '')
        contact_name = self.get_json_argument("contact_name", '')
        phone = self.get_json_argument("phone", '')
        need_tax = self.get_json_argument("need_tax", 0)
        tax_unit = self.get_json_argument("tax_unit", '')
        tax_code = self.get_json_argument("tax_code", '')
        user_remark = self.get_json_argument("user_remark", '')
        if check_param([id, contact_name, phone]):
            return self.render_json(code=1001, msg='参数不全')
        vo = VideoOrder.objects.filter(id=id, user=user).first()
        if not vo:
            return self.render_json(code=1001, msg='订单不存在')
        vo.photo_time = photo_time
        vo.city = city
        vo.contact = contact_name
        vo.phone = phone
        vo.need_tax = need_tax
        vo.tax_unit = tax_unit
        vo.tax_code = tax_code
        vo.user_remark = user_remark
        vo.order_status = VideoOrder.STATE_OBLIGATIONS

        vo.save()

        user.phone=phone
        user.contact_name=contact_name
        user.save()
        remote_ip = self.request.remote_ip
        data = {"appid": cms_config.app_id,
                "openid": vo.user.openid,
                "mch_id": cms_config.mch_id,
                "nonce_str": uuid.uuid1().hex,
                "body": "欢玺视频定制",
                "sign_type": "MD5",
                "out_trade_no": str(vo.order_id),
                "total_fee": str(vo.price*8//10),
                "spbill_create_ip": remote_ip,
                "notify_url": "https://api.joyfulmedia.cn/api/video-order-notify",
                "trade_type": "JSAPI"
                }
        url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'

        sign = wzhifuSDK.get_sign(data)
        data['sign'] = sign
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch(url, method='POST', body=wzhifuSDK.trans_dict_to_xml(data),
                   callback=self.on_response)

    def on_response(self, response):
        if response.error:
            self.render_json(code=1002, msg='系统异常')
        else:
            sign_data = {}
            data = wzhifuSDK.xml_to_dict(response.body.decode('utf-8'))
            if data.get('return_code', '') == 'SUCCESS' and data.get('return_msg', '') == 'OK' and data.get('result_code', '') == 'SUCCESS':
                sign_data['nonceStr'] = uuid.uuid1().hex.upper()
                sign_data['signType'] = 'MD5'
                sign_data['timeStamp'] = str(int(time.time()))
                sign_data['appId'] = cms_config.app_id
                sign_data['package'] = 'prepay_id=' + data.get('prepay_id', '')
                sign_data['sign'] = wzhifuSDK.get_sign(sign_data)
                print(sign_data)
                return self.render_json(data=sign_data)
            else:
                return self.render_json(code=9999, msg='系统错误')


# 首次支付回调
class PayNotify(BaseController):
    def post(self):
        data = wzhifuSDK.xml_to_dict(self.request.body.decode('utf-8'))
        out_trade_no = data.get('out_trade_no')
        total_fee = data.get('total_fee')
        transaction_id = data.get('transaction_id')
        vo = VideoOrder.objects.filter(order_id=out_trade_no).first()
        vo.weixin_order_id = transaction_id
        vo.pay_amount = int(total_fee)
        vo.first_pay_amount = int(total_fee)
        vo.order_status = VideoOrder.STATE_PENDING_ORDERS
        # vo.manager_id = get_random_manager()
        vo.save()
        manger_phones=''
        for manager in User.objects.filter(user_state=1).all():
            if manager.phone:
                manger_phones+=manager.phone+','

        if manger_phones:
            manger_phones=manger_phones[0:-1]
            __business_id = uuid.uuid1()
            params = "{\"code\":\"12345\",\"product\":\"云通信\"}"
            print(send_sms(__business_id, manger_phones, "欢玺传媒", "SMS_156276832", params))

        video_elements = OrderElement.objects.filter(order=vo).all()
        OrderTeam.objects.create(price=vo.price, amount=vo.price * 0.8, rate=0.8, order=vo, order_status=OrderTeam.DPD, state=0)
        for k in video_elements:
            for i in range(k.num):
                OrderProducer.objects.create(price=k.element.price, amount=k.element.price * 0.8, rate=0.8, order=vo, element=k.element, order_status=OrderProducer.DPD, state=1)
        self.write('''<xml>
                    <return_code>SUCCESS</return_code>
                    <return_msg>OK</return_msg>
                    </xml>''')


# 视频类型列表
class VideoTypeList(BaseController):
    def get(self):
        return self.render_json(data=[key.to_dict() for key in VideoType.objects.all()])


# 定制化下单需求
class CategoryList(BaseController):
    def get(self):
        id = self.get_argument("id", '')
        param = [id, ]
        if check_param(param):
            self.render_json(code=1001, msg='参数不全')
            return
        video_type = VideoType.objects.filter(id=id).first()
        if not video_type:
            self.render_json(code=1001, msg='参数错误')
            return
        return self.render_json(data=[key.to_dict() for key in video_type.categories.all()])
